from fastapi import APIRouter, HTTPException
from typing import List, Optional
from uuid import uuid4
from datetime import datetime
import json
from fastapi.responses import StreamingResponse

from app.models.ai_model import AIModel, AIModelCreate, AIModelUpdate, AIModelTest, AIModelTestResult
from app.services.ai_model_service import AIModelService

router = APIRouter()

@router.get("/ai-models", response_model=List[AIModel])
async def get_ai_models():
    """获取所有 AI 模型"""
    service = AIModelService()
    return await service.get_all_models()

@router.get("/ai-models/{model_id}", response_model=AIModel)
async def get_ai_model(model_id: str):
    """获取单个 AI 模型详情"""
    service = AIModelService()
    model = await service.get_model_by_id(model_id)
    if not model:
        raise HTTPException(status_code=404, detail="AI 模型不存在")
    return model

@router.post("/ai-models", response_model=AIModel)
async def create_ai_model(model: AIModelCreate):
    """创建新的 AI 模型"""
    service = AIModelService()
    return await service.create_model(model)

@router.put("/ai-models/{model_id}", response_model=AIModel)
async def update_ai_model(model_id: str, model: AIModelUpdate):
    """更新 AI 模型"""
    service = AIModelService()
    updated_model = await service.update_model(model_id, model)
    if not updated_model:
        raise HTTPException(status_code=404, detail="AI 模型不存在")
    return updated_model

@router.delete("/ai-models/{model_id}")
async def delete_ai_model(model_id: str):
    """删除 AI 模型"""
    service = AIModelService()
    success = await service.delete_model(model_id)
    if not success:
        raise HTTPException(status_code=404, detail="AI 模型不存在")
    return {"message": "AI 模型已删除"}

@router.post("/ai-models/{model_id}/test", response_model=AIModelTestResult)
async def test_ai_model(model_id: str, test_data: AIModelTest):
    """测试 AI 模型"""
    service = AIModelService()
    try:
        print(f"开始测试 AI 模型 ID: {model_id}")
        print(f"测试消息: {test_data.message}")
        
        model = await service.get_model_by_id(model_id)
        if not model:
            print(f"错误: 未找到 ID 为 {model_id} 的模型")
            raise HTTPException(status_code=404, detail="AI 模型不存在")
        
        print(f"找到模型: {model['name']}, 类型: {model['api_type']}")
        
        # 调用实际的 AI 模型 API
        response = await service.test_ai_model(model_id, test_data.message)
        print(f"API 响应: {response}")
        
        return {
            "response": response
        }
    except Exception as e:
        print(f"测试 AI 模型时发生错误: {str(e)}")
        import traceback
        print(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"测试失败: {str(e)}")

@router.post("/ai-models/{model_id}/stream", response_class=StreamingResponse)
async def stream_ai_model(model_id: str, test_data: AIModelTest):
    """测试 AI 模型（流式输出）"""
    service = AIModelService()
    
    try:
        print(f"开始流式测试 AI 模型 ID: {model_id}")
        print(f"测试消息: {test_data.message}")
        
        model = await service.get_model_by_id(model_id)
        if not model:
            print(f"错误: 未找到 ID 为 {model_id} 的模型")
            raise HTTPException(status_code=404, detail="AI 模型不存在")
        
        # 确保模型启用了流式输出
        if not model.get('stream_enabled', False):
            raise HTTPException(status_code=400, detail="此模型未启用流式输出")
        
        print(f"找到模型: {model['name']}, 类型: {model['api_type']}")
        
        # 创建流式响应生成器
        async def generate_stream():
            try:
                async for chunk in service.stream_ai_model(model_id, test_data.message):
                    # 将每个块包装为 SSE 格式
                    yield f"data: {json.dumps({'content': chunk})}\n\n"
            except Exception as e:
                print(f"流式生成错误: {str(e)}")
                yield f"data: {json.dumps({'error': str(e)})}\n\n"
            finally:
                yield "data: [DONE]\n\n"
        
        return StreamingResponse(
            generate_stream(),
            media_type="text/event-stream"
        )
    except Exception as e:
        print(f"流式测试 AI 模型时发生错误: {str(e)}")
        import traceback
        print(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"流式测试失败: {str(e)}") 